<template>
  <div class="home_page">
    <!-- 头部导航栏 -->
    <top-menu></top-menu>
    <!-- 背景图片 -->
    <div class="background">
      <img src="@/assets/wallhaven.png" alt="" />
    </div>
    <!-- 主要窗口 -->
    <main>
      <!-- 机器人登录 -->
      <el-form
        ref="ruleForm"
        :model="formData"
        :rules="botRules"
        class="login_box box">
        <el-form-item label="账号" prop="account">
          <el-input
            v-model.number="formData.account"
            placeholder="机器人账号"
            :readonly="isOnline"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            placeholder="机器人密码"
            :readonly="isOnline"></el-input>
        </el-form-item>
        <el-row :gutter="4">
          <el-col :span="12">
            <el-form-item label="端口" prop="address">
              <el-input
                v-model="formData.address"
                placeholder="Rcon端口"
                :readonly="isOnline"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="rPassword">
              <el-input
                v-model="formData.rPassword"
                placeholder="Rcon密码"
                :readonly="isOnline"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="logFile">
          <template slot="label">
            <span>日志：</span>
            <el-checkbox v-model="formData.encode" :disabled="isOnline">
              GBK编码
            </el-checkbox>
          </template>
          <div class="logFile">
            <el-input
              type="text"
              v-model="formData.logFile"
              placeholder="~/logs/latest.log"
              readonly></el-input>
            <input
              type="file"
              class="fileInput"
              :disabled="isOnline"
              @input="fileInput" />
          </div>
        </el-form-item>
        <el-form-item class="center">
          <el-button type="primary" @click="login" v-if="!isOnline">
            登 录
          </el-button>
          <el-button type="danger" @click="stop" v-else>断 开</el-button>
          <el-button
            type="info"
            style="margin-left: 20px"
            :disabled="isOnline"
            @click="reset">
            重 置
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 信息 -->
      <div class="right_main">
        <el-form :model="otherData" inline class="box right_top">
          <el-row>
            <el-form-item label="历史记录">
              <el-select
                style="width: 180px"
                :value="otherData.his"
                filterable
                @change="changeHistory">
                <el-option
                  v-for="(item, index) in historyList"
                  :key="index"
                  :value="item.account">
                  {{ item.account }}
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="danger"
                circle
                icon="el-icon-delete"
                title="清空历史记录"
                @click="clearHistory"></el-button>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="绑定群聊">
              <el-input
                style="width: 180px"
                :value="groupId"
                placeholder="请输入"
                :readonly="isOnline"
                @input="changeValue($event, 'Set_GroupId')"></el-input>
            </el-form-item>
          </el-row>
        </el-form>
        <div class="box right_bottom">
          <div class="code" ref="scroll" v-if="logsHtml.length > 0">
            <p v-for="(text, index) in logsHtml" :key="index">{{ text }}</p>
            <el-button
              type="danger"
              class="clearLog"
              icon="el-icon-delete"
              circle
              size="large"
              @click="clearLog"></el-button>
          </div>
          <el-result
            v-else
            icon="info"
            title="未连接"
            subTitle="请先登录机器人"></el-result>
        </div>
      </div>
    </main>
    <!-- 配置菜单 -->
    <c-config></c-config>
    <!-- 验证码 -->
    <c-captcha
      v-if="captcha.show"
      :type="captcha.type"
      :url="captcha.url"
      @ok="submitCaptcha"></c-captcha>
  </div>
</template>

<script>
  import { mapGetters } from "vuex";
  import topMenu from "@/components/topMenu.vue";
  import cConfig from "@/components/config.vue";
  import cCaptcha from "@/components/captcha.vue";
  // 引入机器人
  import { botClient, event } from "@/bot/bot.js";

  export default {
    data() {
      return {
        formData: {
          account: undefined,
          password: "",
          address: "",
          rPassword: "",
          logFile: "",
          encode: true,
        },
        botRules: {
          account: [
            { required: true, message: "请输入机器人账号", trigger: "blur" },
          ],
          password: [
            { required: true, message: "请输入机器人密码", trigger: "blur" },
          ],
          address: [{ required: true, message: "请输入端口", trigger: "blur" }],
          rPassword: [
            { required: true, message: "请输入密码", trigger: "blur" },
          ],
          // logFile: [
          //   { required: true, message: "请选择日志地址", trigger: "change" },
          // ],
        },
        otherData: {
          his: "",
          trigger: "#",
        },
        logsHtml: [],
        bot: null,
        captcha: {
          show: false,
          type: undefined,
          url: undefined,
        },
      };
    },
    components: { topMenu, cConfig, cCaptcha },
    watch: {
      logsHtml: {
        deep: true,
        handler(val) {
          // 每次滚动到底部
          this.$nextTick(function () {
            const element = this.$refs.scroll;
            element.scrollTo({
              top: element.scrollHeight,
              behavior: "smooth",
            });
          });
        },
      },
    },
    computed: {
      ...mapGetters([
        "show",
        "historyList",
        "isOnline",
        "groupId",
        "platform",
        "configShow",
      ]),
    },
    mounted() {
      this.$store.dispatch("Set_Show", true);
      this.$store.dispatch("Set_ConfigShow", false);
      this.$store.dispatch("Set_IsOnline", false);
      event.on("bot-close", () => {
        this.stop();
      });
      event.on("bot-captcha", ({ type, url }) => {
        this.captcha.show = true;
        this.captcha.type = type;
        this.captcha.url = url;
      });
      event.on("bot-online", () => {
        console.log("登陆成功");
      });
    },
    methods: {
      // 登录
      login() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.$store.dispatch("Set_History_List", this.formData);
            this.$store.dispatch("Set_IsOnline", true);
            // 开启订阅消息
            event.on("bot-message-watch", (msg) => {
              this.logsHtml.push(msg);
            });

            this.bot = new botClient(
              // 机器人配置
              {
                account: Number(this.formData.account),
                password: this.formData.password,
                platform: this.platform,
              },
              // rcon配置
              {
                port: this.formData.address,
                password: this.formData.rPassword,
              },
              // 读取文件地址
              this.formData.logFile,
              // 文件编码
              this.formData.encode
            );
            this.bot.start();
          } else {
            return false;
          }
        });
      },
      // 重置
      reset() {
        if (!this.isOnline) {
          this.$refs.ruleForm.resetFields();
        }
      },
      // 断开
      stop() {
        event.off("bot-message-watch");
        this.bot.stop();
        this.$store.dispatch("Set_IsOnline", false);
        this.captcha = this.$options.data().captcha;
        this.logsHtml.push("机器人已断开");
      },
      // 清空历史记录
      clearHistory() {
        this.$confirm("确认清空历史记录吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$store.dispatch("Set_History_List", "clear");
            this.$message({
              type: "success",
              message: "清空成功！",
            });
          })
          .catch(() => {});
      },
      // 选择日志文件
      fileInput(ev) {
        this.formData.logFile = String(ev.target.files[0].path);
      },
      // 选中历史记录
      changeHistory(val) {
        if (!this.isOnline) {
          const item = this.historyList.find((ev) => ev.account == val);
          this.formData = JSON.parse(JSON.stringify(item));
        } else {
          this.$message.error("请先断开服务器连接！");
        }
      },
      // 数据更新
      changeValue(ev, name) {
        this.$store.dispatch(name, ev);
      },
      // 提交验证码
      submitCaptcha(value) {
        // 滑块验证码
        if (this.captcha.type === 1) this.bot.captcha(value);
        // 扫码登陆
        if (this.captcha.type === 3) {
          this.bot.qrcode(value);
          // 关闭
          if (value === "close") this.stop();
          // 刷新不关闭
          if (value === "refresh") return;
        }
        // 清空
        this.captcha = this.$options.data().captcha;
      },
      // 清屏
      clearLog() {
        this.logsHtml.splice(0, this.logsHtml.length, "已清屏");
      },
    },
  };
</script>

<style lang="scss">
  .home_page {
    width: 100%;
    height: 100%;
    border-radius: 8px;
    box-shadow: 0 0 10px rgba($color: #000000, $alpha: 0.3);
    position: relative;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .background {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 1;

      img {
        width: 100%;
        height: 100%;
      }
    }

    main {
      height: 370px;
      flex-shrink: 0;
      display: flex;
      align-items: center;
      padding: 10px;
      position: relative;
      z-index: 2;

      .login_box {
        flex-shrink: 0;
        width: 200px;
        height: 100%;

        .logFile {
          position: relative;

          .fileInput {
            position: absolute;
            left: 0;
            opacity: 0;
          }
        }
      }

      .right_main {
        flex-shrink: 0;
        flex: 1;
        height: 350px;
        display: flex;
        flex-direction: column;
        margin-left: 10px;

        .right_top {
          flex-shrink: 0;
          margin-bottom: 10px;
          display: flex;
          flex-wrap: wrap;
          padding-bottom: 0;

          .el-form-item--mini.el-form-item,
          .el-form-item--small.el-form-item {
            margin-bottom: 12px;
          }
        }

        .right_bottom {
          flex: 1;
          flex-shrink: 0;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;

          .code {
            background: rgba($color: #fff, $alpha: 0.6);
            border-radius: 8px;
            height: 230px;
            width: 100%;
            flex-shrink: 0;
            padding: 10px;
            display: inline-block;
            overflow-y: auto;
            overflow-x: hidden;
            position: relative;

            p {
              font-size: 14px;
              word-break: break-all;
              user-select: text;
              line-height: 1.8em;

              &::selection {
                background: #409eff;
                color: #fff;
              }
            }

            .clearLog {
              position: fixed;
              right: 30px;
              bottom: 30px;
              opacity: 0.9;
            }
          }
        }
      }
    }
  }
</style>
